#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：self-practice 
@File    ：RabbitMQConnection.py
@IDE     ：PyCharm 
@Author  ：w50011605
@Email   ：wangqiyu1@xfusion.com
@Date    ：2025/6/25 11:37 
'''

import pika
from pika.channel import Channel

class RabbitMQConnection:
    def __init__(self, host: str = 'localhost'):
        """初始化RabbitMQ连接"""
        self.host = host
        self.connection = None
        self.channel = None

    def connect(self):
        """建立连接并初始化信道"""
        if not self.connection or self.connection.is_closed:
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(self.host))
            self.channel = self.connection.channel()

    def close(self):
        """关闭连接"""
        if self.connection and not self.connection.is_closed:
            self.connection.close()

    def get_channel(self) -> Channel:
        """获取信道"""
        if not self.channel:
            self.connect()
        return self.channel
